package com.leyou.search.scheduler;

import com.leyou.auth.client.AuthClient;
import com.leyou.search.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 定时获取Token
 */
@Component
@Slf4j
public class AppTokenScheduler {
    /**
     * token刷新间隔
     */
    private static final long TOKEN_REFRESH_INTERVAL = 86400000L;
    /**
     * token获取失败后重试的间隔
     */
    private static final long TOKEN_RETRY_INTERVAL = 10000L;

    @Autowired
    private AuthClient authClient;

    @Autowired
    private JwtProperties jwtProperties;

    private String token;//保存成功后token

    /**
     * 每个24小时获取一次Token，如果获取失败，10s后重试
     */
    @Scheduled(fixedRate = TOKEN_REFRESH_INTERVAL)
    public void autoAppAuth() {

        while(true){

            try {
                //请求token
                String token = authClient.authorization(jwtProperties.getApp().getServiceName(),
                        jwtProperties.getApp().getSecret());

                this.token = token;

                log.info("【服务自动获取token】- "+jwtProperties.getApp().getServiceName()+"连接成功");
                break;
            }catch (Exception e){
                try {
                    log.info("【服务自动获取token】- "+jwtProperties.getApp().getServiceName()+"连接失败，10秒后重试...");
                    //10秒后重试
                    Thread.sleep(TOKEN_RETRY_INTERVAL);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
        }

    }

    //获取token的方法
    public String getAppToken() {
        return token;
    }
}

